<?php
require_once("config/db.php");
// start a php array which we will return as ajax to our javascript (eventually)
if (isset($_POST['name'])) {
 	$con=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
	// Check connection
	if (mysqli_connect_errno()) {
	  	echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}

	$name = $_POST['name'];
	$surveyId = $_POST['survey_id'];
	$availability = $_POST['availability'];
	
	$sql = 'SELECT MAX(entryId) FROM surveyResults WHERE survey_id='.$surveyId ;
	$result = mysqli_query($con,$sql);
	$row = mysqli_fetch_array($result);
	$entryId = $row[0]+1;


 	for ($i=0; $i<count($availability); $i++) {
		$weekDay = $availability[$i]['weekDay'];
		$hour = $availability[$i]['hour'];
		$minute = $availability[$i]['minute'];
		$willingness = $availability[$i]['willingness'];
		$sql = 'INSERT INTO surveyResults(survey_id,user_name,entryId,weekDay,hour,minute,availability ) 
				VALUES('.$surveyId.',"'.$name.'",'.$entryId.',"'.$weekDay.'",'.$hour.','.$minute.','.$willingness.')';
						
	if (mysqli_query($con, $sql)) {
    	echo "New record created successfully";
	} else {
    	echo "Error: " . $sql . "<br>" . mysqli_error($con);
	}
	} 
	mysqli_close($con);
}
else
{echo "Please write your name";}
?>